import { defineStore } from "pinia";
import { loginApi, refreshTokenApi } from "@/api/auth";
import { getUserInfo } from "@/api/system/user";
import { resetRouter } from "@/router";
import { store } from "@/store";
import { LoginData } from "@/api/auth/types";
import { UserInfo } from "@/api/system/user/types";
import { useStorage } from "@vueuse/core";
import router from "@/router";
import moment from "moment";

export const useUserStore = defineStore("user", () => {
  // state
  const type = ref();
  const projectCorpType = ref();
  const projectCorpTypes = ref([1, 2, 3, 6, 9]);
  const objectId = ref();
  const projectId = ref();
  const projectName = ref();
  const industryType = ref();
  const token = useStorage("accessToken", "");
  const tokenExpire = useStorage("accessTokenExpire ", 0);
  const name = ref("");
  const avatar = ref("");
  const roles = ref<Array<string>>([]); // 用户角色编码集合 → 判断路由权限
  const perms = ref<Array<string>>([]); // 用户权限编码集合 → 判断按钮权限
  /**
   * 登录调用
   *
   * @param {LoginData}
   * @returns
   */
  function login(loginData: LoginData) {

    return new Promise<any>((resolve, reject) => {
      console.log("userStore-start", new Date().getTime(), loginData);
      loginApi(loginData)
        .then( async (response) => {
          console.log("userStore-success", new Date().getTime(), response);
          if (!response.success) {
            ElMessage.error(response.msg);
            reject(response);
          } else {
            const { tokenType, accessToken, expires } = response.data;
            //这里实现页面跳转
            //   router.push({ path: "/dashboard", query: { editToken: response.data.editToken } });

            switch (response.data.actionCode) {
              //无需任何操作
              case 0:
                token.value = tokenType + " " + accessToken; // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
                tokenExpire.value = moment().add(expires, "ms").toDate().getTime();
                resolve(response.data.actionCode);
                break;
              //完善信息
              case 1:
                if (response.data.type == 2)
                  router.push({ path: "/corpEdit", query: { editToken: response.data.editToken } });
                if (response.data.type == 3)
                  router.push({ path: "/constructorEdit", query: { editToken: response.data.editToken } });
                break;
              //跳转工程项目信息页面
              // case 2:
              //   ElMessageBox.confirm("存在审核失败的项目，是否跳转修改", "提示", {
              //     confirmButtonText: "确定",
              //     cancelButtonText: "取消",
              //     type: "warning",
              //   }).then(() => {
              //     token.value = tokenType + " " + accessToken; // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
              //     // if (response.data.type == 2) router.push({ path: "/corp/project/projectInfo" });
              //     // if (response.data.type == 5) router.push({ path: "/manager/project/projectInfo" });
              //     resolve(response.data.actionCode);
              //   });
              //   break;
              //跳转审核失败项目
              case 3:
                router.push({ path: "/failprojectedit", query: { editToken: response.data.editToken } });
                break;
              default:
                token.value = tokenType + " " + accessToken; // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
                tokenExpire.value = moment().add(expires, "ms").toDate().getTime();
                resolve(response.data.actionCode);
                break;
            }
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  function getInfo() {
    return new Promise<UserInfo>((resolve, reject) => {
      getUserInfo()
        .then(({ data }) => {
          if (!data) {
            return reject("Verification failed, please Login again.");
          }
          if (!data.roles || data.roles.length <= 0) {
            reject("getUserInfo: roles must be a non-null array!");
          }
          objectId.value = data.objectId;
          name.value = data.name;
          type.value = data.type;
          roles.value = data.roles;
          perms.value = data.perms;
          localStorage.setItem("usertype", data.type.toString());
          let usertypeName = "";
          switch (data.type.toString()) {
            case "1":
              usertypeName = "SysUser"; //主管单位
              break;
            case "2":
              usertypeName = "Corp"; //企业
              break;
            case "3":
              usertypeName = "Constructor"; //建设单位
              break;
            case "4":
              usertypeName = "Bank"; //银行
              break;
            case "5":
              usertypeName = "Manager"; //项目管理员
              break;
            case "6":
              usertypeName = "Commander"; //指挥部
              break;
          }
          localStorage.setItem("usertypeName", usertypeName);
          if (data.project && data.project.projectId) {
            projectId.value = data.project.projectId;
            projectName.value = data.project.name;
            industryType.value = data.project.industryType;
            localStorage.setItem("project", JSON.stringify(data.project));
            //缓存项目行业分类
            localStorage.setItem("industryType", data.project.industryType);
            if (data.type == 2 && data.project.lumpContractorCorpId == data.objectId)
              localStorage.setItem("isLumpContractor", "1");
            else localStorage.setItem("isLumpContractor", "0");
          }
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  function getProjectCorpRoleInfo() {
    return new Promise((resolve, reject) => {
      getProjectCorpRole()
        .then((resp) => {
          projectCorpType.value = resp.data;
          resolve(resp);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 注销
  function logout() {
    return new Promise<void>((resolve, reject) => {
      // logoutApi()
      //   .then(() => {
      //     resetRouter();
      //     resetToken();
      //     location.reload(); // 清空路由
      //     // localStorage.clear();
      //     resolve();
      //   })
      //   .catch((error) => {
      //     reject(error);
      //   });

      new Promise<void>(() => {
        resetRouter();
        resetToken();
        location.reload(); // 清空路由
        localStorage.removeItem("accessToken");
        localStorage.removeItem("project");
        localStorage.removeItem("usertypeName");
        // localStorage.clear();
        resolve();
      }).catch((error) => {
        reject(error);
      });
    });
  }

  /**
   * 更新当前项目
   * @param currentType
   */
  function updateCurrentType(currentType: any) {
    projectId.value = currentType;
  }

  /**刷新token */
  function refreshToken() {
    // token.value = accessToken;
    // tokenExpire.value = expires;
    return new Promise<string>((resolve, reject) => {
      // token.value = accessToken;
      // tokenExpire.value = expires;
      // resolve();
      refreshTokenApi()
        .then((res) => {
          token.value = res.data.tokenType + " " + res.data.accessToken; // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          tokenExpire.value = moment().add(res.data.expires, "ms").toDate().getTime();
          console.log("refreshTokenApi" + token.value);
          resolve(token.value);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 重置
  function resetToken() {
    token.value = "";
    name.value = "";
    avatar.value = "";
    roles.value = [];
    perms.value = [];
  }
  return {
    token,
    tokenExpire,
    name,
    avatar,
    roles,
    perms,
    projectName,
    projectId,
    industryType,
    type,
    projectCorpType,
    projectCorpTypes,
    login,
    getInfo,
    logout,
    resetToken,
    updateCurrentType,
    getProjectCorpRoleInfo,
    /**
     * 当前登录用户ID
     */
    objectId,
    refreshToken,
  };
});

// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}
